<?php

namespace app\admin\controller;
use app\common\controller\Backend;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use fast\Random;
use app\admin\model\Fields;
/**
 *
 *
 * @icon fa fa-circle-o
 */
class Import extends Backend
{
    public function _initialize()
    {
        $this -> year = $this -> request -> get('year',date('Y'));
        $this->model = new \app\admin\model\Project([],$this -> year);
    }
    public function index()
    {
        $filePath = ROOT_PATH . DS . 'public' . DS . 'import/import.xlsx';
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = 'nsig_project_2020';
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            $fieldArr[] = $v['COLUMN_NAME'];
            // if ($importHeadType == 'comment') {
            //     $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            // } else {
            //     $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            // }
        }


        $insert = [];

        if (!$PHPExcel = $reader->load($filePath)) {
            $this->error(__('Unknown data format'));
        }
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        // $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $allRow = min($allRow, 200);
        // $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
        // echo  $maxColumnNumber;

        $maxColumnNumber = 24;

        // echo $maxColumnNumber;
        $fields = [];
        // echo  $startheaderrow;
        for ($currentRow = 3; $currentRow <= 3; $currentRow++) {
            for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                // if($val)
                $fields[] = $val;
            }
        }

        $msg = '';
        $errors = [];
        $addDataAll = [];
        $logDataAll = [];
        for ($currentRow = 4; $currentRow <= $allRow; $currentRow++) {
            $error = '';
            $values = [];
            for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                // if(is_object($val))
                //     echo $val->__toString();
                $values[] = is_object($val) ? $val->__toString() : ($val == null ? '' : trim($val));
            }
            $temp = array_combine($fields, $values);
            $res = [];
            foreach ($temp as $k => $v) {
                // echo $k.",".$v."<br>";
                if (in_array($k,$fieldArr) && $k !== '') {
                    $res[$k] = $v;
                }
            }

            // pr($res);


            $addData = $this->importcheckfileds($res);
            $addData['library_id'] = 2;
            $addData['library_name'] = '签约库';
            // pr($addData);
            $addData['pno'] = Random::uuid();

            pr($addData);
            $row = Db::name('project_2020') -> where(['name'=> $temp['name']])->find();
            if($row)
            {
                // $error .=$temp['name'].'已存在<br>';

                continue;
            }
            $type = input('type',0);
            if($type)
                Db::name('project_2020')->insert($addData);
            // }
            // else
            //     $errors[] = $addData['name'].":<br>".$error;
        }
         // $errors_str = implode("<br>",$errors);
        // if($errors_str)
        //     pr($errors);
        // else
        // {
        //     pr($addDataAll);
        //     $results=Db::name('project_2020')->insertAll($addDataAll);
        //     pr($results);
        // }

        // pr($addDataAll);
    }



    public function importcheckfileds($params) {
        // pr($params);
        // pr($this->fiveindustryArr);
        //
        $fields_list = Db::name('fields')->where(['status'=>1,'table_name'=>'project'])->select();
        // pr($fields_list);
        // $data = [];
        foreach ($fields_list as $key => $value) {


            $field = $value['item_id'];
            // echo $field;
            if(!isset($params[$field]) )
                continue;
            // echo $field;
            // echo $params[$field];
            if($params[$field] == '')
            {
                unset($params[$field]);
                continue;
                // $params[$field] = null;
            }


            if($value['item_type'] == "select")
            {

                $params[$field] = preg_replace('/[^\x{4e00}-\x{9fa5}a-zA-Z0-9]/u',",",$params[$field]);
                $rule = json_decode($value['item_rule'], true);
                $name_field = str_replace('id','name', $field);
                $name_field_value = $params[$field];

                // echo $params[$field];
                $name_value = explode(",",$params[$field]);
                if(is_string($rule['datasource'])){
                    $tb_name = $rule['datasource'];
                    $params[$field] =  getSelectId($tb_name,$name_value);
                }else
                    $params[$field] = array_search($params[$field], $rule['datasource']);



                if(!$params[$field])
                {
                    unset($params[$field]);
                    continue;
                }

                $params[$name_field] = $name_field_value;

            }

            if($value['item_type'] == "price")
            {
                if($params[$field] == PENDING_TEXT)
                    $params[$field] = PENDING;
                if($params[$field] == ZERO )
                {
                    unset($params[$field]);
                    continue;
                }
            }
            if($value['item_type'] == "datetime" || $value['item_type'] == "date")
            {
                // var_dump($params[$field]);

                if($params[$field] == PENDING_TEXT)
                {
                    $params[$field] = PENDING;
                    $params[$field.'_desc'] = PENDING_TEXT;
                }
                else
                {
                    $params[$field.'_desc'] = dateFormatter($params[$field],1);
                    $params[$field] = dateFormatter($params[$field],0);

                }
            }

            if($value['item_type'] == 'radio')
            {
                if($params[$field] == '是')
                    $params[$field] = '1';
                elseif($params[$field] == '否')
                    $params[$field] = '1';
                else{
                    unset($params[$field]);
                    continue;
                }

            }


        }
        // pr($params);
        return $params;

    }


    public function checkrequire($type = null){
        $list = $this->model->select();
        $where['table_name'] = 'project';
        $where['status'] = 1;
            // $where['item_library'] = ['in',"0,{$library_id}"];
        $fields_list =Fields::where($where)->select();
        $dataAll = [];
        foreach ($list as $kk => $row) {
            $required_arr = [];
            foreach ($fields_list as $key => $value) {


                $item_required = $value['item_required'] ? json_decode($value['item_required'],true):'';
                if(isset($row['library_id']) && $row['library_id'] && $item_required )
                {
                    $is_required = $item_required[$row['library_id']]['is_required'];

                    if($is_required == '1'   && $value['item_class'] != 'capital' && $value['item_class'] != 'agreement')
                    {

                        if(!$row[$value['item_id']] && !$row['tmp_'.$value['item_id']])
                            $required_arr[] = $value['item_label'];

                    }
                }
            }
            if(!$row['domestic_capital'] && !$row['tmp_foreign_capital'] && !$row['tmp_domestic_capital'] && !$row['foreign_capital'])
                $required_arr[] = '内外资(至少填一项)';



            if(isset($row['library_id']) && $row['library_id']==2)
            {
                if((!$row['carrier_id'] && $row['carrier_id'] != 5 && !$row['carrier_id_relation']) && ($row['tmp_carrier_id'] && $row['tmp_carrier_id'] != 5 && !$row['tmp_carrier_id_relation']))
                    $required_arr[] = '载体面积';

                if(($row['is_access'] == '是' &&  !$row['access_time'])|| ($row['tmp_is_access'] == '是' &&  !$row['tmp_access_time']))
                    $required_arr[] = '准入时间';
                if(($row['is_land'] == '是' &&  !$row['land_time']) ||  ($row['tmp_is_land'] == '是' &&  !$row['tmp_land_time']))
                    $required_arr[] = '拿地时间';

                if(!$row['framework_agreement_time'] && !$row['invesment_agreement_time'] && !$row['tmp_framework_agreement_time'] && !$row['tmp_invesment_agreement_time'])
                    $required_arr[] = '框架、正式协议(至少填一项)';
            }

            $required_text = implode(",",$required_arr);
            echo $row['name']."<br>";
            pr($required_arr);
            // $dataAll[] = ['id'=>$row['id'],'required_text'=>$required_text];
            if($type)
                Db::name('project_2020')->update(['id'=>$row['id'],'required_text'=>$required_text]);
            // $row->required_text = $required_text;
            // $row->save();
        }
        // pr($dataAll);
        // $this->model->saveAll($dataAll);
    }
}